package com.smartian.scan.filesearch.task.runnable;

import android.text.TextUtils;

import com.smartian.scan.filesearch.bean.PathFile;
import com.smartian.scan.filesearch.bean.SearchResult;
import com.smartian.scan.filesearch.bean.StringPath;
import com.smartian.scan.filesearch.interfaces.ISearchTaskEngine;
import com.smartian.scan.filesearch.interfaces.ITaskCallback;

import java.util.List;
import java.util.Stack;

public class StackTaskRunnable implements Runnable {

    private final ISearchTaskEngine task;
    private Stack<String> stackPaths = null;
    private ITaskCallback callback;
    private String dir;

    public StackTaskRunnable(ISearchTaskEngine task, String dir, ITaskCallback searchCallback) {
        this.stackPaths = new Stack<>();
        this.task = task;
        this.dir = dir;
        this.callback = searchCallback;

    }

    @Override
    public void run()   {

        this.stackPaths.push(this.dir);

        if(callback!=null){
            callback.onTaskStart(this.dir);
        }

       while (!stackPaths.empty()){

           String path = stackPaths.pop();
           if(TextUtils.isEmpty(path)){
               continue;
           }

           StringPath stringPath = new StringPath(path);
           String rootPath = stringPath.getRootPath();

           SearchResult searchResult = null;
           try {
               SearchResult  result = task.doInBackground(rootPath);
               if(result!=null){
                   searchResult = StringPath.transform(result,stringPath);
               }
               if(searchResult!=null && callback!=null){
                   callback.onTaskFiles(rootPath, searchResult);
               }
           }catch (Exception e){
               e.printStackTrace();
               if(callback!=null){
                   callback.onTaskError(rootPath,e);
               }
           }
           if(searchResult==null) continue;

           List<PathFile> dirs = searchResult.getDirs();

           if(dirs==null) continue;

           for (int i=0;i<dirs.size();i++){
               stackPaths.push(dirs.get(i).getDirPath());
           }
       }

       if(callback!=null){
           callback.onTaskFinish(dir);
       }

    }
}
